<?php
declare (strict_types=1);

namespace app\common\middleware;

use app\common\exception\DomainInvalidException;
use app\school\logic\school\admin\SchoolDomain as SchoolDomainLogic;

/**
 * 机构域名绑定
 */
class SchoolDomain
{
    public function handle($request, \Closure $next)
    {
        // 注入当前请求的用户MID,此MID仅供前台接口使用
        $request->mid = 0;
        // 机构ID
        $request->mhm_id = (int)$request->header('E-MHM-ID') ?: 1;
        // 机构独立域名
        $request->mhm_sdn = 0;
        // 机构当前域名
        $request->mhm_host = '';
        // 主站PC域名
        $request->pc_host = config('eduline.appinfo.pc_host');

        try {
            // 获取页面请求来源
            $referer = $request->header('referer') ?: $request->header('origin');
            // 正则匹配域名
            $sdnhost = $this->pregDomain($referer ?: $request->pc_host);
            $pchost  = $this->pregDomain($request->pc_host);
            // 仅支持PC和H5端域名
            $deviceType = strtolower($request->header('e-device-type') ?: '');
            $isDev      = $sdnhost === 'localhost' || $sdnhost === '127.0.0.1';

            if (!$isDev && in_array($deviceType, ['pc', 'h5']) && $sdnhost != $pchost) {
                $dns = $sdnhost ? @dns_get_record($sdnhost, DNS_CNAME) : false;
                if ($dns) {
                    // 通过cname自定义域名访问
                    $dns  = current($dns);
                    $host = $dns['target'] ?? '';
                } else {
                    // 通过二级域名访问
                    $host = $sdnhost;
                }

                // 匹配出域名前缀
                if (preg_match('/^(https?:\/\/)?([^\.]+)/', $host, $match)) {
                    // 获取机构id
                    $request->mhm_id = app(SchoolDomainLogic::class)->getMatchMhmId($match[2]);

                    if (!$request->mhm_id) {
                        throw new DomainInvalidException('无效域名');
                    }
                    // 指定为机构域名
                    $request->mhm_sdn = 1;
                    // 获取当前机构生效域名
                    $request->mhm_host = app(SchoolDomainLogic::class)->getEffectivePcDomain($request->mhm_id);

                }

            }
        } catch (\Exception $e) {
            throw new DomainInvalidException('域名无效', $e->getMessage());
        }

        return $next($request);
    }

    /**
     * 获取域名
     *
     * @param $url
     * @return string
     */
    private function pregDomain($url)
    {
        $sdnhost = '';
        if (preg_match('/^(https?:\/\/)?([^\/|:]+)/', $url, $match)) {
            $sdnhost = $match[2];
        }

        return $sdnhost;
    }
}